﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;

using ARD.Common;
using ARD.Configuration;
using ARD.Data;

namespace SharpEntitiesTest
{
    public class DataAccessLayer : IDisposable
    {
        private IDb db = null;
        private XmlDefinitions sql;

        public DataAccessLayer(string configFile, string sqlDefFile, string databaseId)
        {
            this.db = DbFactory.CreateDatabase(configFile, string.Format("//databases/database_descriptor[@id='{0}']", databaseId));
            this.sql = new XmlDefinitions(sqlDefFile, false, this.db.ResourceVersion);
        }

        #region IDisposable Members

        public void Dispose()
        {
            if(this.db != null)
            {
                lock (this.db)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        #endregion

        public DataRowCollection GetRows(string sqlStatementId, ParamDescriptorCollection parameters)
        {

            string sSqlTemplate = this.sql[sqlStatementId];
            IDbCommand cmd = db.CreateQueryCommand(sSqlTemplate, parameters);
            IDbDataAdapter da = db.CreateDataAdapter(cmd, true);
            DataTable dt = db.FillDataTable(da);

            return dt.Rows;
        }

        public DataRowCollection GetEmployeesByCity(string city)
        {
            ParamDescriptorCollection parameters = new ParamDescriptorCollection();
            parameters.Add(new ParamDescriptor("city", DataType.UnicodeString, ParameterDirection.Input, 0, city));
            return GetRows("select_employees_by_city", parameters);
        }

    }
}
